package com.example.forhelp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    MyBroadcastReceiver myBroadcastReceiver;  // 广播接收者

    private Button btnHelp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        myBroadcastReceiver = new MyBroadcastReceiver();  // 实例化广播接收者
        String action = "Help";
        IntentFilter intentFilter = new IntentFilter(action);
        registerReceiver(myBroadcastReceiver, intentFilter);  // 注册广播
        btnHelp = (Button) findViewById(R.id.btn_help);
        btnHelp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                // 定义广播事件
                intent.setAction("Help");
                sendBroadcast(intent);  // 发送广播
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myBroadcastReceiver);
    }
}